<template>
  <Dialog v-model="dialogVisible" :title="title" width="800px">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <!-- 任务名称 -->
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入任务名称" />
      </el-form-item>

      <!-- 任务描述 -->
      <el-form-item label="任务描述" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入任务描述" />
      </el-form-item>

      <!-- 启用状态 -->
      <el-form-item label="启用状态" prop="enable">
        <el-switch v-model="formData.enable" :active-value="1" :inactive-value="0" />
      </el-form-item>

      <!-- 同意书模版 -->
      <el-form-item label="同意书模版" prop="algorithmId">
        <el-select
          v-model="formData.consentFormTemplateId"
          placeholder="请选择同意书模版"
          class="!w-full"
        >
          <el-option
            v-for="consentFormTemplate in consentFormTemplateOptions"
            :key="consentFormTemplate.id"
            :value="consentFormTemplate.id"
            :label="consentFormTemplate.name"
          />
        </el-select>
      </el-form-item>

      <!-- 关联算法 -->
      <el-form-item label="关联算法" prop="algorithmId">
        <el-select v-model="formData.algorithmId" placeholder="请选择算法" class="!w-full">
          <el-option
            v-for="algorithm in algorithmOptions"
            :key="algorithm.id"
            :value="algorithm.id"
            :label="algorithm.name"
          />
        </el-select>
      </el-form-item>

      <!-- 模型选择 -->
      <el-form-item label="模型选择" prop="model">
        <el-radio-group v-model="formData.model">
          <el-radio value="GRM">GRM</el-radio>
          <el-radio value="GPCM">GPCM</el-radio>
          <el-radio value="3PL">3PL</el-radio>
          <el-radio value="2PL">2PL</el-radio>
          <el-radio value="1PL">1PL</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 选题策略 -->
      <el-form-item label="选题策略" prop="selectionStrategy">
        <el-radio-group v-model="formData.selectionStrategy">
          <el-radio value="MLWI">MLWI</el-radio>
          <el-radio value="KL">KL</el-radio>
          <el-radio value="MFI">MFI</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 能力值估计方法 -->
      <el-form-item label="能力值估计方法" prop="estimationMethod">
        <el-radio-group v-model="formData.estimationMethod">
          <el-radio value="EAP">EAP</el-radio>
          <el-radio value="MLE">MLE</el-radio>
          <el-radio value="MAP">MAP</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 关联题库 -->
      <el-form-item label="关联题库" prop="taskLibraries">
        <div class="w-full">
          <!-- 表头 -->
          <div class="flex items-center gap-10px mb-10px text-14px font-500 text-gray-600">
            <div style="flex: 1">题库选择</div>
            <div style="width: 120px">最大答题</div>
            <div style="width: 150px">终止阈值</div>
            <div style="width: 80px">操作</div>
          </div>

          <!-- 题库列表 -->
          <div
            v-for="(library, index) in formData.taskLibraries"
            :key="index"
            class="flex items-center gap-10px mb-10px"
          >
            <div style="flex: 1">
              <el-select
                v-model="library.storeId"
                placeholder="请选择题库"
                style="width: 100%"
                :class="{ 'error-border': !library.storeId }"
              >
                <el-option
                  v-for="store in storeOptions"
                  :key="store.id"
                  :value="store.id"
                  :label="store.name"
                />
              </el-select>
            </div>
            <div style="width: 120px">
              <el-input
                type="number"
                v-model="library.questionCount"
                placeholder="最大答题"
                :class="{ 'error-border': !library.questionCount }"
              />
            </div>
            <div style="width: 150px">
              <el-input-number
                v-model="library.terminationThreshold"
                placeholder="终止阈值"
                :class="{ 'error-border': !library.terminationThreshold }"
              />
            </div>
            <div style="width: 80px">
              <el-button type="danger" size="small" @click="removeLibrary(index)">删除</el-button>
            </div>
          </div>

          <!-- 添加题库按钮 -->
          <el-button type="primary" size="small" @click="addLibrary" class="mt-10px"
            >添加题库</el-button
          >
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">
        <Icon icon="ep:check" class="mr-5px" /> 提交
      </el-button>
      <el-button @click="resetForm"> <Icon icon="ep:refresh" class="mr-5px" /> 重置 </el-button>
      <el-button @click="dialogVisible = false"> 取消 </el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as CatTaskApi from '@/api/pm/cattask'
import * as AlgorithmApi from '@/api/system/algorithm'
import * as CatStoreApi from '@/api/pm/catstore'
import * as ConsentTemplateApi from '@/api/system/consenttemplate'

defineOptions({ name: 'PmCatTaskForm' })

const message = useMessage()

const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()
const mode = ref<'create' | 'update'>('create')
const title = computed(() => (mode.value === 'create' ? '新增' : '编辑'))

const formData = ref<any>({
  id: undefined,
  name: '',
  remark: '',
  enable: '1',
  algorithmId: '',
  model: 'GRM',
  selectionStrategy: 'MLWI',
  estimationMethod: 'EAP',
  taskLibraries: [],
  consentFormTemplateId: ''
})

const formRules = reactive({
  name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  //remark: [{ required: true, message: '请输入任务描述', trigger: 'blur' }],
  enable: [{ required: true, message: '请选择启用状态', trigger: 'change' }],
  algorithmId: [{ required: true, message: '请选择关联算法', trigger: 'change' }],
  consentFormTemplateId: [{ required: true, message: '请选择同意书模版', trigger: 'change' }],
  model: [{ required: true, message: '请选择模型', trigger: 'change' }],
  selectionStrategy: [{ required: true, message: '请选择题策略', trigger: 'change' }],
  estimationMethod: [{ required: true, message: '请选择能力值估计方法', trigger: 'change' }],
  taskLibraries: [{ required: true, message: '请至少添加一个题库', trigger: 'change' }]
})

const algorithmOptions = ref<{ id: string; name: string }[]>([])
const storeOptions = ref<{ id: string; name: string }[]>([])
const consentFormTemplateOptions = ref<{ id: string; name: string }[]>([])

// 加载算法选项
const loadAlgorithmOptions = async () => {
  try {
    const data = await AlgorithmApi.getAlgorithmPageQuery({ pageNo: 1, pageSize: 100 })
    algorithmOptions.value =
      data?.map((item: any) => ({
        id: String(item.id),
        name: item.name
      })) || []
  } catch (error) {
    console.error('加载算法选项失败:', error)
  }
}

// 加载题库选项
const loadStoreOptions = async () => {
  try {
    const data = await CatStoreApi.getCatStorePageQuery()
    storeOptions.value =
      data?.map((item: any) => ({
        id: String(item.id),
        name: item.name
      })) || []
  } catch (error) {
    console.error('加载题库选项失败:', error)
  }
}

// 加载同意书模版选项
const loadConsentFormTemplateOptions = async () => {
  try {
    const data = await ConsentTemplateApi.consentTemplateActive()
    consentFormTemplateOptions.value =
      data?.map((item: any) => ({
        id: String(item.id),
        name: item.formName
      })) || []
  } catch (error) {
    console.error('加载失败:', error)
  }
}

const open = async (openMode: 'create' | 'update', id?: number) => {
  mode.value = openMode
  dialogVisible.value = true
  resetForm()

  // 加载选项数据
  await Promise.all([loadAlgorithmOptions(), loadStoreOptions(), loadConsentFormTemplateOptions()])

  if (openMode === 'update' && id) {
    formLoading.value = true
    try {
      const data = await CatTaskApi.getCatTaskDetail(id)
      formData.value = {
        ...data,
        algorithmId: data.algorithm ? String(data.algorithm.id) : '',
        consentFormTemplateId: data.consentFormTemplateId ? String(data.consentFormTemplateId) : '',
        taskLibraries: (data.stores || []).map((item: any) => {
          item.storeId = String(item.id)
          return item
        })
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

const emit = defineEmits(['success'])

// 验证题库字段
const validateLibraries = () => {
  const libraries = formData.value.taskLibraries || []
  if (libraries.length === 0) {
    message.error('请至少添加一个题库')
    return false
  }

  for (let i = 0; i < libraries.length; i++) {
    const library = libraries[i]
    if (!library.storeId) {
      message.error(`第${i + 1}个题库：请选择题库`)
      return false
    }
    if (!library.questionCount) {
      message.error(`第${i + 1}个题库：请输入最大答题数`)
      return false
    }
    if (!library.terminationThreshold) {
      message.error(`第${i + 1}个题库：请输入终止阈值`)
      return false
    }
  }
  return true
}

const submitForm = async () => {
  const valid = await formRef.value?.validate()?.catch(() => false)
  if (!valid) return

  // 验证题库字段
  if (!validateLibraries()) return

  formLoading.value = true
  try {
    if (mode.value === 'create') {
      await CatTaskApi.addCatTask(formData.value)
      message.success('新增成功')
    } else {
      await CatTaskApi.editCatTask(formData.value)
      message.success('修改成功')
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 添加题库
const addLibrary = () => {
  formData.value.taskLibraries.push({
    storeId: '',
    questionCount: '',
    terminationThreshold: ''
  })
}

// 删除题库
const removeLibrary = (index: number) => {
  formData.value.taskLibraries.splice(index, 1)
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    remark: '',
    enable: '1',
    algorithmId: '',
    model: 'GRM',
    selectionStrategy: 'MLWI',
    estimationMethod: 'EAP',
    taskLibraries: []
  }
  formRef.value?.resetFields?.()
}
</script>

<style scoped>
.error-border :deep(.el-input__wrapper) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 1px #f56c6c inset !important;
}

.error-border :deep(.el-select__wrapper) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 1px #f56c6c inset !important;
}

.error-border :deep(.el-input-number__wrapper) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 1px #f56c6c inset !important;
}
</style>
